import json
import threading
from tkinter import Label, Button, Entry
from tkinter.ttk import Combobox

from kf.dict_enum_generate.dsConfig import select_dict
import os
import pyperclip

from util.comm.AsyncTask import AsyncTask
from util.comm.cmd_util import wrap_with_try_except
from util.database.cmd import run_cmd
from util.window.config_window.config_button import create_config_button
from util.comm.path import getConfigPath, getPath
from util.comm.msg_util import msg
from util.window.config_window.config_module import config_select, select_reload_button


class Enums():
    def __init__(self):
        super().__init__()

    def frame(self, tab):
        self.tab = tab

        self.elements = []

        self.config_path = getPath()
        self.config_select_db_path = os.path.join(self.config_path, 'config.json')
        select_moudle = config_select(tab, None)
        self.config_select_db_button = select_reload_button().create(tab, select_moudle)
        self.config_select_db_button.pack(side='right', fill=None, expand=False, anchor='ne')
        self.elements.append(self.config_select_db_button)

        self.dropdown = select_moudle.create(10)
        self.dropdown.pack(side='right', fill='x', expand=False, anchor='ne', padx=5, pady=5)
        self.elements.append(self.dropdown)

        self.label = Label(tab, text="输入字典字段名：")
        self.label.pack()
        self.elements.append(self.label)

        self.entry = Entry(self.tab)
        self.entry.pack()
        self.elements.append(self.entry)

        self.button = Button(self.tab, text="生成枚举类", command=self.print_entry_sync)
        self.button.pack()
        self.elements.append(self.button)

    def select_item(self, event):
        index = self.dropdown.current()
        print('select_item----%s' % index)
        self.config = self.drop_config_list[index]

    def print_entry_sync(self):
        if hasattr(self, 'sync_flag') and self.sync_flag == '1':
            msg('正在处理,请勿重复操作')
            return
        self.sync_flag = '1'
        wrap_print_entry = wrap_with_try_except(self.print_entry)
        AsyncTask(threading.Thread(target=wrap_print_entry, args=()), lambda: self.reset_sync()).execute_async()

    def reset_sync(self):
        self.sync_flag = '0'

    def print_entry(self):
        if hasattr(self, 'label_out'):
            self.label_out.destroy()
        self.out_file_path = select_dict(self.entry.get(), self.dropdown.config_info)
        if self.out_file_path is None:
            return
        self.label_out = Label(self.tab, text="枚举类已生成：%s" % self.out_file_path)
        self.label_out.pack()
        self.elements.append(self.label_out)
        run_cmd(f"notepad {self.out_file_path}")
        with open(self.out_file_path, 'r', encoding='utf-8') as file:
            content = file.read()
            pyperclip.copy(content)
        delete_file(self.out_file_path)


def delete_file(file_path):
    try:
        os.remove(file_path)
        print(f"File {file_path} has been deleted successfully.")
    except OSError as e:
        print(f"Error: {file_path} : {e.strerror}")
